<script lang="ts" setup>
import { getCurrentInstance, reactive, ref } from 'vue'
import { onLoad, onPageScroll, onReady } from '@dcloudio/uni-app'
import TnTabs from '@tuniao/tnui-vue3-uniapp/components/tabs/src/tabs.vue'
import TnTabsItem from '@tuniao/tnui-vue3-uniapp/components/tabs/src/tabs-item.vue'
import TnPhotoAlbum from '@tuniao/tnui-vue3-uniapp/components/photo-album/src/photo-album.vue'
import TnLazyLoad from '@tuniao/tnui-vue3-uniapp/components/lazy-load/src/lazy-load.vue'
import TnAvatar from '@tuniao/tnui-vue3-uniapp/components/avatar/src/avatar.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import { useScrollTransparentNavbar } from '@/hooks'
import useZPaging from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging.js'
import PageContainer from '@/components/page-container/index.vue'
import circlesPost from '@/api/circlesPost.js'
import { FILE_URL, SYSTEM_CONFIG } from '@/api/config.js'

const paging = ref(null)
useZPaging(paging)
// 导航栏的高度
const navbarHeight = ref(0)
const instance = getCurrentInstance()
const {
  triggerElementId,
  navbarOpacity,
  opacityScrollHandle,
  init: initTransparentScroll,
} = useScrollTransparentNavbar(instance)
// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}
const state = reactive({
  loading: false,
  topicId: 0,
  topicName: '',
  currentTabIndex: 0,
  sortValue: 'hottest',
  tabsData: [
    {
      text: '推荐',
    },
    {
      text: '新发',
    },
    {
      text: '新回',
    },
  ],
  circlesPostLists: [],
  systemConfig: {
    circles: {
      topic_detail_bg: '',
    },
  },
})

const clickTabs = (index: number) => {
  if (index == 0) {
    state.sortValue = 'hottest'
  } else if (index == 1) {
    state.sortValue = 'newest_publish'
  } else {
    state.sortValue = 'newest_reply'
  }
  paging.value.reload(true)
}

const jumpMap = (
  longitude: any,
  latitude: any,
  location: any,
  poiaddress: any
) => {
  tnNavPage(
    `/pagesA/location?longitude=${longitude}&latitude=${latitude}&location=${location}&poiaddress=${poiaddress}`
  )
}
const navUserHomePage = (uId: number) => {
  tnNavPage(`/pagesA/userhome?otherUserId=${uId}`)
}
const navCirclesDetailPage = (circlesId: number) => {
  tnNavPage(`/circlesPages/detail?circlesId=${circlesId}`)
}
const navCirclesPostDetailPage = (circlesPostId: number) => {
  tnNavPage(`/circlesPostPages/detail?circlesPostId=${circlesPostId}`)
}
const navVideoLists = (circlesPostId: number) => {
  tnNavPage(`/circlesPostPages/video?circlesPostId=${circlesPostId}`)
}
const queryList = (pageNo: any, pageSize: any) => {
  circlesPost
    .topicCirclesPostLists({
      topic_name: state.topicName,
      page: pageNo,
      page_size: pageSize,
      weigh: state.sortValue,
    })
    .then((res) => {
      console.log(res, 'getCirclesPostLists')
      if (res.code == 1) {
        res.data.forEach((dynamic) => {
          if (dynamic.attachment_type == 'image') {
            if (Array.isArray(dynamic.attachment)) {
              // 遍历 attachment 数组
              dynamic.attachment = dynamic.attachment.map((attachment) => {
                return `${FILE_URL}${attachment}`
              })
            }
          }
        })
        paging.value.complete(res.data)
      }
    })
    .catch((err) => {
      console.log(err, 'getCirclesPostLists')
      paging.value.complete(false)
    })
}

onLoad((options) => {
  state.systemConfig = uni.getStorageSync(SYSTEM_CONFIG)
  if (!options?.topicName) {
    uni.showModal({
      title: '提示',
      content: '参数错误',
      showCancel: false,
      success: () => {
        uni.navigateBack()
      },
    })
    return
  }
  state.topicName = options.topicName
  state.topicId = options.topicId
})

onReady(() => {
  initTransparentScroll()
})
onPageScroll((e) => {
  opacityScrollHandle(e.scrollTop)
})
</script>

<template>
  <PageContainer :placeholder-bottom="true">
    <TnNavbar
      fixed
      home-icon="discover-fill"
      :bg-color="`rgba(255, 255, 255, ${navbarOpacity})`"
      :bottom-shadow="false"
      :placeholder="false"
      @init-finish="navbarInitFinishHandle"
    />
    <!-- 顶部背景 -->
    <view
      class="top-bg"
      :style="
        'background: url(' +
        FILE_URL +
        state.systemConfig.circles.topic_detail_bg +
        '); background-repeat: no-repeat;background-size: cover;background-position: center center;'
      "
    />

    <!-- 话题信息 -->
    <view class="community-summary">
      <view class="summary-content">
        <view class="summary-info">
          <view class="title">#{{ state.topicName }}#</view>
        </view>
      </view>
    </view>

    <view :id="triggerElementId" class="topic-list">
      <TnTabs
        v-model="state.currentTabIndex"
        :scroll="false"
        :bottom-shadow="false"
        bar-color="#ffa929"
        active-color="#000"
      >
        <TnTabsItem
          v-for="(item, index) in state.tabsData"
          :key="index"
          :title="item.text"
          @click="clickTabs(index)"
        />
      </TnTabs>
      <view class="tn-gray-disabled_border tn-border-bottom" />
      <z-paging
        ref="paging"
        v-model="state.circlesPostLists"
        use-page-scroll
        @query="queryList"
      >
        <template #refresher="{ refresherStatus }">
          <CustomRefresher :status="refresherStatus" />
        </template>

        <view class="topic-item">
          <view
            v-for="(item, index) in state.circlesPostLists"
            :key="index"
            class="dynamic"
          >
            <view class="graphic-card">
              <!-- 简要信息 -->
              <view class="brief-info">
                <view class="brief-info__content">
                  <view class="brief-info__avatar">
                    <TnAvatar
                      v-if="item.user.is_vip == 1"
                      :url="FILE_URL + item.user.avatar"
                      :border="true"
                      :shadow="true"
                      img-mode="aspectFill"
                      size="lg"
                      badge="icon-vip-diamond-fill"
                      :badge-config="{
                        absoluteCenter: false,
                        absolutePosition: {
                          top: '60rpx',
                          right: '-10rpx',
                        },
                        fontSize: '35',
                        textColor: '#FFB800',
                        bgColor: '#FFFFFF',
                        size: '40',
                      }"
                      @click="navUserHomePage(item.user.id)"
                    />
                    <TnAvatar
                      v-else
                      :url="FILE_URL + item.user.avatar"
                      :border="true"
                      :shadow="true"
                      img-mode="aspectFill"
                      size="lg"
                      @click="navUserHomePage(item.user.id)"
                    />
                  </view>
                  <view class="brief-info__data">
                    <view class="title tn-text-ellipsis-1">
                      <text @click="navUserHomePage(item.user.id)">
                        {{ item.user.nickname }}
                      </text>
                      <image
                        v-if="item.user.grade_icon != ''"
                        :src="FILE_URL + item.user.grade_icon"
                        class="user-level-img"
                      />
                    </view>
                    <view class="desc tn-text-ellipsis-1">
                      {{ item.update_date }}
                    </view>
                  </view>
                </view>
                <view class="brief-info__operation">
                  <slot name="briefOperation">
                    <view class="brief-info__operation" />
                  </slot>
                </view>
              </view>
              <!-- 内容容器 -->
              <view class="container">
                <!-- 内容 -->
                <view class="content">
                  <!-- 标签和内容 -->
                  <view class="content__tags">
                    <view
                      v-for="(tagItem, tagIndex) in item.topics_name"
                      :key="tagIndex"
                      class="tag-item"
                    >
                      #{{ tagItem }}
                    </view>
                  </view>
                  <view
                    class="content__data"
                    @tap.stop="navCirclesPostDetailPage(item.id)"
                  >
                    <text>{{ item.content }}</text>
                  </view>
                </view>
                <!-- 图片列表 -->
                <view
                  v-if="item.attachment_type == 'image'"
                  class="images"
                  @tap.stop="navCirclesPostDetailPage(item.id)"
                >
                  <!-- 一张图片 -->
                  <view v-if="item.attachment.length === 1" class="images-one">
                    <TnLazyLoad :src="item.attachment[0]" />
                  </view>
                  <!-- 两张图片 -->
                  <view v-if="item.attachment.length === 2" class="images-two">
                    <TnPhotoAlbum :data="item.attachment" :column="2" />
                  </view>
                  <!-- 三张图片 -->
                  <view
                    v-if="item.attachment.length === 3"
                    class="images-three"
                  >
                    <view class="image-wrapper-left">
                      <view class="image-container">
                        <TnLazyLoad :src="item.attachment[0]" />
                      </view>
                    </view>
                    <view class="image-wrapper-right">
                      <view class="image-container">
                        <TnLazyLoad :src="item.attachment[1]" />
                      </view>
                      <view class="image-container">
                        <TnLazyLoad :src="item.attachment[2]" />
                      </view>
                    </view>
                  </view>
                  <!-- 四张图片 -->
                  <view v-if="item.attachment.length === 4" class="images-four">
                    <TnPhotoAlbum :data="item.attachment" :column="2" />
                  </view>
                  <TnPhotoAlbum
                    v-if="item.attachment.length >= 5"
                    :data="item.attachment"
                  />
                </view>

                <!-- 视频 -->
                <view
                  v-if="item.attachment_type == 'video'"
                  class="content-video"
                  @click="navVideoLists(item.id)"
                >
                  <view class="video-icon">
                    <TnIcon name="video-fill" size="100" color="#FFFFFF" />
                  </view>
                  <video
                    class="video-data"
                    :src="FILE_URL + item.attachment"
                    :muted="true"
                    object-fit="cover"
                    :enable-progress-gesture="false"
                    :show-loading="false"
                    :show-play-btn="false"
                    :show-center-play-btn="false"
                    :show-fullscreen-btn="false"
                    :controls="false"
                    :autoplay="false"
                    :enable-play-gesture="false"
                    :loop="true"
                  />
                </view>

                <!-- 语音 -->
                <view v-if="item.attachment_type == 'voice'" class="audio">
                  <luch-audio
                    :play.sync="true"
                    :name="item.user.nickname"
                    author="录制"
                    :poster="FILE_URL + item.user.avatar"
                    :src="FILE_URL + item.attachment"
                    :autoplay="false"
                  />
                </view>
              </view>

              <!-- 链接 -->
              <view v-if="item.attachment_type == 'link'" class="link">
                <uni-link
                  :href="item.attachment"
                  :text="item.attachment"
                  color="#007BFF"
                  copy-tips="链接已复制"
                  font-size="18"
                />
              </view>

              <!-- 底部信息 -->
              <view v-if="item.location !== ''" class="location-info">
                <TnButton
                  plain
                  border-color="tn-grey-disabled"
                  custom-class="custom-button-class"
                  @click="
                    jumpMap(
                      item.longitude,
                      item.latitude,
                      item.location,
                      item.poiaddress
                    )
                  "
                >
                  <TnIcon name="location-fill" color="tn-blue" />
                  <view class="location-name">{{ item.location }}</view>
                </TnButton>
              </view>
              <view class="bottom-info">
                <view class="bottom-info__left">
                  <view class="tag-circles">
                    <view class="tn-flex-center-center">
                      <view class="circles-pic">
                        <view
                          class="circles-image"
                          :style="
                            'background-image: url(' +
                            FILE_URL +
                            item.circles.image +
                            ')'
                          "
                        />
                      </view>
                      <view
                        class="circles-name tn-text-ellipsis-1"
                        @tap.stop="navCirclesDetailPage(item.circles.id)"
                      >
                        {{ item.circles.name }}</view
                      >
                    </view>
                  </view>
                </view>
                <view class="bottom-info__right">
                  <!-- 底部右侧数据 -->
                  <view class="count-item-data">
                    <TnIcon name="eye" />
                    <view class="count">{{ item.view_total }}</view>
                  </view>
                  <view class="count-item-data">
                    <TnIcon name="message" />
                    <view class="count"> {{ item.comment_total }} </view>
                  </view>
                  <view v-if="item.plate == 'dynamic'" class="count-item-data">
                    <TnIcon name="like" />
                    <view class="count">{{ item.like_total }}</view>
                  </view>
                </view>
              </view>
            </view>
            <view
              style="border-bottom: 20rpx solid var(--tn-color-gray-light)"
            />
          </view>
        </view>
      </z-paging>
    </view>
  </PageContainer>
</template>

<style lang="scss" scoped>
@use '../styles/topic/detail.scss';
@use '@/static/css/graphic-card.scss';
</style>
